//
//  FTWCache.m
//  FTW
//
//  Created by Soroush Khanlou on 6/28/12.
//  Copyright (c) 2012 FTW. All rights reserved.
//

#import "FTWCache.h"

@interface FTWCache ()
+(NSString*)getCacheDirectory;
@end

@implementation FTWCache


//无条件清空所有的
+(void)cleanAll{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
         [fileManager removeItemAtPath:[self getCacheDirectory] error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
}



//重新设置缓存，条件清空
+ (void)resetCache {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error = nil;
        
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:[self getCacheDirectory] error:&error];
        
        if (fileList!=nil) {
            
            NSInteger size = [fileList count];
            
            NSMutableString *path = [[NSMutableString alloc]init];
            NSMutableDictionary *fileAttributes = [[NSMutableDictionary alloc]init];
            
            NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYYMMdd"];
            
            for (int i = 0; i<size; i++) {
                
                [path setString:[[self getCacheDirectory] stringByAppendingPathComponent:[fileList objectAtIndex:i]]];;
                
                [fileAttributes removeAllObjects];
                [fileAttributes addEntriesFromDictionary:[fileManager attributesOfItemAtPath:path error:nil]];
                
                if (fileAttributes != nil&&[fileAttributes count]>0) {
                    
//                    NSRange dd= [path rangeOfString:@"3f8530d9dc89b07bb863b5870ed98a9f"];
//                    if (dd.length>0) {
//                        int y = 0;
//                    }
//                     NSDate* modDate = [fileAttributes objectForKey:NSFileModificationDate];
                    
                    NSDate* modDate = [fileAttributes objectForKey:NSFileModificationDate];
                    NSString * modDataString=[dateformatter stringFromDate:modDate];
                    modDate = [dateformatter dateFromString:modDataString];
                    
                    
                    NSDate *nowData=[NSDate date];
                    NSString * nowDataString=[dateformatter stringFromDate:nowData];
                    nowData = [dateformatter dateFromString:nowDataString];
                    
                        NSLog(@"扫描到文字缓存:    %@",modDate);
                    if ([modDate compare:nowData]==NSOrderedAscending) {// mod < now
                        [fileManager removeItemAtPath:path error:nil];
                        NSLog(@"删除过期文字的缓存---------------: %@",modDate);
                    }
                }else{
                    [fileManager removeItemAtPath:path error:nil];
                }
            }
            }  
        
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    });
}



//返回本应用的本地缓存目录
+ (NSString*)getCacheDirectory {
	NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cacheDirectory = [paths objectAtIndex:0];
	cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"QQDataCaches"];
	return cacheDirectory;
}

//从缓存中获取数据
+ (NSData*) objectForKey:(NSString*)key {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *filePath = [[self getCacheDirectory] stringByAppendingPathComponent:key];
	
	if ([fileManager fileExistsAtPath:filePath])//如果要请求的缓存数据文件存在
	{
       NSDictionary *fileParm = [fileManager attributesOfItemAtPath:filePath error:nil];
        
        if (fileParm != nil&&[fileParm count]>0) {
            
            NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYYMMdd"];
            
            NSDate* modDate = [fileParm objectForKey:NSFileModificationDate];
            NSString * modDataString=[dateformatter stringFromDate:modDate];
            modDate = [dateformatter dateFromString:modDataString];
            modDate = [FTWCache getLocData:modDate];
            
            
            NSDate *nowData=[NSDate date];
            NSString * nowDataString=[dateformatter stringFromDate:nowData];
            nowData = [dateformatter dateFromString:nowDataString];
            nowData = [FTWCache getLocData:nowData];
            
            NSLog(@"本次读取的文字缓存:    %@||%@",modDate,nowData);
            if ([modDate compare:nowData]==NSOrderedAscending) {// mod < now
                [fileManager removeItemAtPath:filePath error:nil];
                NSLog(@"删除本次读取过期文字的缓存---------------: %@",modDate);
            }
            
        }else{
            [fileManager removeItemAtPath:filePath error:nil];
        }
        
        
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        return data;
	}
	return nil;
}



//把数据写入缓存，
+ (void) setObject:(NSData*)data forKey:(NSString*)key {
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *filename = [[self getCacheDirectory] stringByAppendingPathComponent:key];

    BOOL isDir = YES;
	if (![fileManager fileExistsAtPath:[self getCacheDirectory] isDirectory:&isDir]) {
		[fileManager createDirectoryAtPath:[self getCacheDirectory] withIntermediateDirectories:NO attributes:nil error:nil];
	}
	
	NSError *error;
	@try {
		[data writeToFile:filename options:NSDataWritingAtomic error:&error];
	}
	@catch (NSException * e) {
		//TODO: error handling maybe
	}
}


+(NSDate*)getLocData:(NSDate*)date{
    
    NSTimeZone *zone =[NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localDate =[date  dateByAddingTimeInterval: interval];
    return localDate;
}


@end
